<template>
  <div class="community-container">
    <div class="community-bulletin">
      <van-notice-bar
          left-icon="volume"
          background="#FFFBE6"
          color="#E6A23C"
          :text="communityNotice"
      />
    </div>

    <div class="search-container">
      <van-search
          v-model="searchValue"
          placeholder="寻找邻居、话题或帮助..."
          shape="round"
          background="transparent"
          @search="onSearch"
      />
    </div>

    <div class="quick-actions">
      <van-grid :border="false" :column-num="3">
        <van-grid-item text="邻里集市" @click="toMarket">
          <template #icon>
            <van-icon name="shopping-cart-o" size="28" color="#FFC107" />
          </template>
        </van-grid-item>
      </van-grid>
    </div>

    <van-tabs v-model:active="activeTab" class="tab-nav-container" @change="onTabChange">
      <van-tab
          v-for="tab in tabNames"
          :key="tab.name"
          :title="tab.title"
          :name="tab.name"
      >
        <post-list
            :posts="tabs[tab.name].posts"
            :loading="tabs[tab.name].loading"
            :has-more="tabs[tab.name].hasMore"
            @load-more="loadMore(tab.name)"
            @post-click="goToPostDetail"
            @update-post="updatePostData"
        />
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import PostList from '../components/PostList.vue';
import axios from '@/utils/axios';
import { showToast } from 'vant';

const router = useRouter();
const route = useRoute();
const searchValue = ref('');
const communityNotice = ref('');
const activeTab = ref('hot');
const tabNames = [
  { name: 'hot', title: '热门' },
  { name: 'discussion', title: '讨论' },
  { name: 'help', title: '求助' },
];
const toMarket = () =>{
  router.push("neighborMarket")
}
const tabs = reactive({
  hot: { posts: [], page: 1, loading: false, hasMore: true },
  discussion: { posts: [], page: 1, loading: false, hasMore: true },
  help: { posts: [], page: 1, loading: false, hasMore: true },
});

const pageSize = 10;

const fetchNotice = async () => {
  try {
    const response = await axios.get('/api/notice/latest');
    const noticeData = response.data;
    communityNotice.value = noticeData ? `${noticeData.title} ${noticeData.content}` : '欢迎来到邻里社区，共建美好家园！';
  } catch (error) {
    console.error('Failed to fetch notice:', error);
    communityNotice.value = '欢迎来到邻里社区，共建美好家园！';
  }
};

const jump = () => {
  router.push('/neighborMarket');
};

const goToPostDetail = (postId) => {
  router.push({
    name: 'postDetail',
    params: { id: postId },
  });
};

const onSearch = () => {
  if (searchValue.value.trim()) {
    router.push({
      name: 'search',
      query: { q: searchValue.value },
    });
  } else {
    showToast('请输入搜索内容');
  }
};

const getPosts = async (type) => {
  const tab = tabs[type];
  if (tab.loading || !tab.hasMore) return;

  tab.loading = true;
  const apiUrl = {
    hot: '/api/posts/getHotPosts',
    discussion: '/api/posts/getDiscussionPosts',
    help: '/api/posts/getHelpPosts',
  }[type];

  try {
    const response = await axios.get(`${apiUrl}?page=${tab.page}&pageSize=${pageSize}`);
    console.log(response)
    const responseData = response.data || {};
    const newData = responseData || responseData.data || [];

    if (tab.page === 1) {
      tab.posts = newData;
    } else {
      tab.posts = [...tab.posts, ...newData];
    }
    tab.hasMore = newData.length >= pageSize;
  } catch (error) {
    console.error(`Failed to fetch ${type} posts:`, error);
    showToast('加载失败，请重试');
    tab.hasMore = false;
  } finally {
    tab.loading = false;
  }
};

const onTabChange = (name) => {
  if (tabs[name].posts.length === 0) {
    getPosts(name);
  }
};

const loadMore = (type) => {
  tabs[type].page += 1;
  getPosts(type);
};

const updatePostData = (updatedPost) => {
  const currentPosts = tabs[activeTab.value].posts;
  const index = currentPosts.findIndex((p) => p.postId === updatedPost.postId);
  if (index !== -1) {
    Object.assign(currentPosts[index], updatedPost);
  }
};

watch(
    () => route.query.refresh,
    (newVal) => {
      if (newVal === 'true') {
        Object.keys(tabs).forEach(key => {
          tabs[key].posts = [];
          tabs[key].page = 1;
          tabs[key].hasMore = true;
        });
        getPosts('hot');
        fetchNotice();
        router.replace({ query: { ...route.query, refresh: undefined } });
      }
    }
);

onMounted(() => {
  getPosts('hot');
  fetchNotice();
});

onActivated(() => {
  getPosts('hot');
  fetchNotice();
});
</script>

<style scoped>
.community-container {
  padding-bottom: 50px;
  background-color: var(--background);
  min-height: 100vh;
}

.community-bulletin {
  padding: 12px 16px 8px;
}

.search-container {
  padding: 0 16px 16px;
}

.search-container .van-search {
  padding: 0;
}

.search-container .van-search__content {
  background-color: var(--card-bg) !important;
  border-radius: 30px;
  box-shadow: var(--shadow);
}

.search-container .van-field__left-icon .van-icon {
  color: var(--primary);
}

.quick-actions {
  padding: 0 16px 20px;
}

.quick-actions .van-grid-item {
  box-shadow: var(--shadow);
  border-radius: var(--border-radius);
  overflow: hidden;
}

.quick-actions .van-grid-item__content {
  background-color: var(--card-bg) !important;
  padding: 6px 8px;
}

.tab-nav-container {
  padding-bottom: 10px;
  background-color: var(--background);
}

.tab-nav-container :deep(.van-tabs__wrap) {
  height: auto;
  padding: 0 16px;
  background-color: transparent;
  box-shadow: none;
}

.tab-nav-container :deep(.van-tab__text--ellipsis) {
  font-weight: 500;
  color: var(--text-light);
}

.tab-nav-container :deep(.van-tabs__line) {
  background-color: var(--primary);
  width: 25px;
}

.tab-nav-container :deep(.van-tab--active .van-tab__text--ellipsis) {
  color: var(--primary);
}
</style>